package com.tiantianyuegou.activity;

import android.accounts.Account;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.tiantianyuegou.R;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.NetworkUtils;
import com.tiantianyuegou.util.StringUtils;
import com.tiantianyuegou.util.Tools;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 注册
 */
public class RegisterActivity extends BaseActivity implements View.OnClickListener ,TextWatcher {
//    http://hjtech.wicp.net:8080/jishitongxun-api//vcode/get?phone=15036035654&type=1
    private EditText edt_register_number, edt_getcode,edt_register_login_account;
    private Button btn_next, btn_getcode;
    //private int iTime = 60;// 倒计时60秒
    private TimeCount time;
    private EditText edt_register_pelese_account;
    LoadingDialog loadingDialog;
    String vCode;
    String TAG = "RegisterActivity";
    String registerNum;
    String getCode;
    String getAccount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
      Tools.changeSystemBar(this);
        setTitle(R.string.register_title);
        initViews();

    }

    @Override
    public void findViewByIds() {
        edt_register_login_account = (EditText) findViewById(R.id.edt_register_login_account);
        edt_register_number = (EditText) findViewById(R.id.edt_register_account);
        edt_getcode = (EditText) findViewById(R.id.edt_getcode);
        btn_getcode = (Button) findViewById(R.id.btn_getcode);
        btn_next = (Button) findViewById(R.id.btn_next);
    }

    @Override
    public void initListener() {
        edt_register_login_account.addTextChangedListener(this);
        edt_register_number.addTextChangedListener(this);
        edt_getcode.addTextChangedListener(this);
        time = new TimeCount(this, 60000, 1000);
        loadingDialog = new LoadingDialog(this);
        btn_next.setOnClickListener(this);
        btn_getcode.setOnClickListener(this);

    }

    @Override
    public void initData() {

    }
    public void luanchActivity() {
       getAccount = edt_register_login_account.getText().toString().trim();
        getCode = edt_getcode.getText().toString().trim();
        registerNum = edt_register_number.getText().toString().trim();
        if (TextUtils.isEmpty(getAccount)) {
            showMsg("请输入登陆账号");
            return;
        } else if (!StringUtils.checkPhone(registerNum)) {
            showMsg("登录帐号格式错误");
            return;
        }
        if (TextUtils.isEmpty(registerNum)) {
            showMsg("请输入登陆密码");
            return;
        } else if (!StringUtils.checkPhone(registerNum)) {
            showMsg("手机号码格式错误");
            return;
        }
        if (TextUtils.isEmpty(getCode)) {
            showMsg("请输入验证码");
            return;
        }
        if (!getCode.equals(vCode)) {
            showMsg("验证码错误");
            return;
        }
        Intent next = new Intent();
        next.putExtra("phone", registerNum);
        next.putExtra("code", vCode);
        next.putExtra("account", getAccount);
        next.setClass(RegisterActivity.this, SettingPwdActivity.class);
        startActivity(next);
        finish();

    }


    public void getCode() {
        if (!NetworkUtils.isNetworkAvailable(this)) {
            showMsg("请检查您的网络");
            return;
        }
        getCode = edt_getcode.getText().toString().trim();
        registerNum = edt_register_number.getText().toString().trim();
        if (TextUtils.isEmpty(registerNum)) {
            showMsg("请输入手机号码");
            return;
        }
        if (!StringUtils.checkPhone(registerNum)) {
            showMsg("手机号码格式错误");
            return;
        }

        loadingDialog.showDialog();
        loadingDialog.setMsg("正在获取验证码");
        RequestParams params = new RequestParams();
        params.addBodyParameter("phone", registerNum);
        params.addBodyParameter("type", 1 + "");
        Log.e("TAG", "tcMobile=" + registerNum);
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.GET_CODE, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                loadingDialog.dismiss();
                Log.e(TAG, "onSuccess response.result  "
                        + response.result);
                if (TextUtils.isEmpty(response.result)) {
                    showMsg("获取失败");
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        vCode = jsonObject.getString("vcode");
                        Log.e("验证码=", vCode);
                        if (code.equalsIgnoreCase("100")) {
                            time.start();
                            String message = "获取成功";
                            if (jsonObject.has("message")) {
                                message = jsonObject.getString("message");
                            }
                        } else if (code.equalsIgnoreCase("101")) {
                            Log.e("验证码=", "获取失败");
                            showMsg("获取失败");
                        }else if (code.equalsIgnoreCase("102")){
                            Log.e("验证码=", "参数提交不完整");
                            showMsg("参数提交不完整");
                        }else if (code.equalsIgnoreCase("103")){
                            Log.e("验证码=", "帐号已被注册");
                            showMsg("帐号已被注册");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        showMsg("手机号码已被注册");
                    }
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                loadingDialog.dismiss();
                showMsg("当前网络不可用，请检查网络设置");
            }
        });

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_next:
                luanchActivity();

                break;
            case R.id.btn_getcode:
                getCode();
                break;
            default:
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String phone=edt_register_number.getText().toString();
        String code=edt_getcode.getText().toString();
        if(phone!=null&&!"".equals(phone)&&code!=null&&!"".equals(code)){
            btn_next.setEnabled(true);
            btn_next.setAlpha(1.0f);
        }else{
            btn_next.setEnabled(false);
            btn_next.setAlpha(0.5f);
        }

    }
    /**
     * 时间计时类
     */
    class TimeCount extends CountDownTimer {
        Activity activity;

        public TimeCount(Activity activity, long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            this.activity = activity;
        }

        /**
         * 计时过程
         *
         * @param millisUntilFinished
         */
        @SuppressLint("NewApi")
        @Override
        public void onTick(long millisUntilFinished) {
            btn_getcode.setClickable(false);
            btn_getcode.setBackground(activity.getResources().getDrawable(R.drawable.btn_getcode_timecount_bg));
            btn_getcode.setTextColor(getResources().getColor(R.color.textcolor_3));
            btn_getcode.setText(millisUntilFinished / 1000 + "S后重发");
        }

        /**
         * 计时完毕时触发
         */
        @SuppressLint("NewApi")
        @Override
        public void onFinish() {
            btn_getcode.setText(R.string.register_get_code);
            btn_getcode.setClickable(true);
            btn_getcode.setBackground(activity.getResources().getDrawable(R.drawable.btn_getcode_bg));
            btn_getcode.setTextColor(getResources().getColor(R.color.bg_button_normal));

        }
    }
}
